package com.auction.task;

import com.auction.dto.OrderDTO;
import com.auction.mapper.AddressBookMapper;
import com.auction.mapper.AuctionMapper;
import com.auction.mapper.BidMapper;
import com.auction.pojo.AddressBook;
import com.auction.pojo.Auction;
import com.auction.pojo.Bid;
import com.auction.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 拍卖定时任务
 */
@Slf4j
@Component
public class AuctionTask {

    @Autowired
    private AuctionMapper auctionMapper;

    @Autowired
    private BidMapper bidMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    /**
     * 每分钟扫描已结束的拍卖
     * 将状态更新为已结束，并为最高出价者自动创建订单
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    @Transactional
    public void endAuctions() {
        log.info("开始扫描已结束的拍卖...");
        LocalDateTime now = LocalDateTime.now();

        // 查找已结束但状态仍为活跃的拍卖
        List<Auction> endedAuctions = auctionMapper.selectEndedActiveAuctions(now);

        for (Auction auction : endedAuctions) {
            try {
                processEndedAuction(auction);
            } catch (Exception e) {
                log.error("处理已结束拍卖时出错，拍卖ID：{}，错误：{}", auction.getId(), e.getMessage(), e);
            }
        }

        log.info("结束拍卖扫描，处理了{}个已结束的拍卖", endedAuctions.size());
    }

    /**
     * 处理已结束的拍卖
     */
    private void processEndedAuction(Auction auction) {
        log.info("处理已结束拍卖：ID={}, 标题={}", auction.getId(), auction.getTitle());

        // 更新拍卖状态为已结束
        auction.setStatus("FINISHED");
        auction.setUpdateTime(LocalDateTime.now());
        auctionMapper.update(auction);

        // 查询最高出价
        Bid highestBid = bidMapper.selectHighestBid(auction.getId());

        if (highestBid != null) {
            // 更新最高出价状态为竞拍成功
            highestBid.setStatus(2); // 2表示竞拍成功
            highestBid.setUpdateTime(LocalDateTime.now());
            bidMapper.updateBidStatus(highestBid.getId(), 2);

            // 更新其他出价状态为竞拍失败
            bidMapper.updateOtherBidsStatus(auction.getId(), highestBid.getId(), 3); // 3表示竞拍失败

            log.info("拍卖[{}]结束，最高出价用户ID：{}，价格：{}",
                    auction.getId(), highestBid.getUserId(), highestBid.getBidPrice());

            // 从Redis中删除相关缓存
            String auctionKey = "auction:" + auction.getId();
            redisTemplate.delete(auctionKey);
            redisTemplate.delete(auctionKey + ":bids");

            // 自动创建订单
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setAuctionId(auction.getId());
            Long addressBookId = addressBookMapper.getDefaultAddressIdByUserId(highestBid.getUserId());
            orderDTO.setShippingAddressId(addressBookId);
            try {
                Long orderId = orderService.create(orderDTO, highestBid.getUserId());
                log.info("已为拍卖[{}]的最高出价者创建订单：{}", auction.getId(), orderId);
            } catch (Exception e) {
                log.error("创建订单失败：{}", e.getMessage(), e);
            }

        } else {
            log.info("拍卖[{}]结束，无人出价", auction.getId());
        }
    }
}